/**
 * AI代码生成服务
 * 集成AI编辑器，实现智能代码生成
 */

export interface DatabaseSchema {
  tables: TableSchema[]
  relationships: TableRelationship[]
}

export interface TableSchema {
  name: string
  comment?: string
  fields: FieldSchema[]
  indexes: IndexSchema[]
  businessType?: 'master' | 'transaction' | 'lookup' | 'log'
  suggestedAPIs?: string[]
}

export interface FieldSchema {
  name: string
  type: string
  nullable: boolean
  primaryKey: boolean
  foreignKey?: ForeignKeyInfo
  comment?: string
  businessRole?: 'id' | 'name' | 'status' | 'timestamp' | 'amount' | 'reference'
}

export interface ForeignKeyInfo {
  referencedTable: string
  referencedField: string
  relationshipType: 'one-to-one' | 'one-to-many' | 'many-to-one'
}

export interface TableRelationship {
  fromTable: string
  toTable: string
  type: 'one-to-one' | 'one-to-many' | 'many-to-many'
  description: string
}

export interface IndexSchema {
  name: string
  fields: string[]
  unique: boolean
  type: string
}

export interface BusinessDomain {
  name: string
  tables: string[]
  description: string
  suggestedModules: string[]
}

export interface AIPromptContext {
  framework: string
  language: string
  database: string
  businessDomain: BusinessDomain
  tableSchema: TableSchema
  relatedTables: TableSchema[]
  requirements: string[]
}

export interface GeneratedCode {
  type: 'controller' | 'service' | 'model' | 'dto' | 'repository'
  filename: string
  content: string
  description: string
  dependencies: string[]
}

export class AICodeGeneratorService {
  /**
   * 分析数据库结构，推断业务逻辑
   */
  async analyzeDatabase(schema: DatabaseSchema): Promise<BusinessDomain[]> {
    const domains: BusinessDomain[] = []
    
    // 1. 表名语义分析
    const tableGroups = this.groupTablesByDomain(schema.tables)
    
    // 2. 关系分析
    const relationships = this.analyzeRelationships(schema)
    
    // 3. 业务领域推断
    for (const [domainName, tables] of Object.entries(tableGroups)) {
      const domain: BusinessDomain = {
        name: domainName,
        tables: tables.map(t => t.name),
        description: this.generateDomainDescription(tables, relationships),
        suggestedModules: this.suggestModules(tables)
      }
      domains.push(domain)
    }
    
    return domains
  }

  /**
   * 生成AI提示词
   */
  generatePrompt(context: AIPromptContext): string {
    const { framework, language, tableSchema, businessDomain } = context
    
    return `
# 代码生成任务

## 项目信息
- 框架: ${framework}
- 语言: ${language}
- 业务领域: ${businessDomain.name}

## 数据表结构
表名: ${tableSchema.name}
业务用途: ${tableSchema.comment || '待推断'}
字段信息:
${tableSchema.fields.map(f => `- ${f.name}: ${f.type} ${f.comment ? `// ${f.comment}` : ''}`).join('\n')}

## 业务需求
${context.requirements.map(req => `- ${req}`).join('\n')}

## 生成要求
请生成完整的${framework}项目代码，包括：
1. 实体类/模型 (Model/Entity)
2. 数据访问层 (Repository/DAO)
3. 业务逻辑层 (Service)
4. 控制器层 (Controller)
5. 数据传输对象 (DTO)

要求代码：
- 遵循最佳实践和设计模式
- 包含完整的CRUD操作
- 添加适当的注释和文档
- 包含数据验证和异常处理
- 符合RESTful API规范
    `
  }

  /**
   * 调用AI服务生成代码
   */
  async generateCode(prompt: string): Promise<GeneratedCode[]> {
    // 这里集成具体的AI服务 (如OpenAI、Claude、本地模型等)
    try {
      // 模拟AI调用
      const response = await this.callAIService(prompt)
      return this.parseAIResponse(response)
    } catch (error) {
      console.error('AI代码生成失败:', error)
      throw new Error('AI代码生成服务暂时不可用')
    }
  }

  /**
   * 智能推荐API端点
   */
  suggestAPIEndpoints(tableSchema: TableSchema): string[] {
    const endpoints: string[] = []
    const tableName = tableSchema.name
    const entityName = this.toCamelCase(tableName)
    
    // 基础CRUD
    endpoints.push(`GET /${tableName} - 查询${entityName}列表`)
    endpoints.push(`GET /${tableName}/{id} - 获取${entityName}详情`)
    endpoints.push(`POST /${tableName} - 创建${entityName}`)
    endpoints.push(`PUT /${tableName}/{id} - 更新${entityName}`)
    endpoints.push(`DELETE /${tableName}/{id} - 删除${entityName}`)
    
    // 根据字段推荐特殊端点
    const hasStatus = tableSchema.fields.some(f => f.name.includes('status'))
    if (hasStatus) {
      endpoints.push(`PUT /${tableName}/{id}/status - 更新${entityName}状态`)
    }
    
    const hasCreateTime = tableSchema.fields.some(f => 
      f.name.includes('create') || f.name.includes('time')
    )
    if (hasCreateTime) {
      endpoints.push(`GET /${tableName}/recent - 获取最近的${entityName}`)
    }
    
    return endpoints
  }

  /**
   * 生成业务逻辑提示
   */
  generateBusinessLogicHints(tableSchema: TableSchema): string[] {
    const hints: string[] = []
    
    // 分析字段特征
    tableSchema.fields.forEach(field => {
      if (field.name.includes('amount') || field.name.includes('price')) {
        hints.push(`${field.name}字段需要金额计算和验证逻辑`)
      }
      if (field.name.includes('status')) {
        hints.push(`${field.name}字段需要状态流转控制`)
      }
      if (field.name.includes('email')) {
        hints.push(`${field.name}字段需要邮箱格式验证`)
      }
      if (field.name.includes('phone')) {
        hints.push(`${field.name}字段需要手机号格式验证`)
      }
    })
    
    return hints
  }

  // 私有方法
  private groupTablesByDomain(tables: TableSchema[]): Record<string, TableSchema[]> {
    const groups: Record<string, TableSchema[]> = {}
    
    tables.forEach(table => {
      const domain = this.extractDomainFromTableName(table.name)
      if (!groups[domain]) {
        groups[domain] = []
      }
      groups[domain].push(table)
    })
    
    return groups
  }

  private extractDomainFromTableName(tableName: string): string {
    // 简单的领域提取逻辑，可以根据实际情况优化
    const commonPrefixes = ['sys_', 'user_', 'order_', 'product_', 'payment_']
    
    for (const prefix of commonPrefixes) {
      if (tableName.startsWith(prefix)) {
        return prefix.replace('_', '')
      }
    }
    
    // 默认按第一个单词分组
    const parts = tableName.split('_')
    return parts[0] || 'common'
  }

  private analyzeRelationships(schema: DatabaseSchema): TableRelationship[] {
    // 分析外键关系
    const relationships: TableRelationship[] = []
    
    schema.tables.forEach(table => {
      table.fields.forEach(field => {
        if (field.foreignKey) {
          relationships.push({
            fromTable: table.name,
            toTable: field.foreignKey.referencedTable,
            type: field.foreignKey.relationshipType,
            description: `${table.name}.${field.name} -> ${field.foreignKey.referencedTable}.${field.foreignKey.referencedField}`
          })
        }
      })
    })
    
    return relationships
  }

  private generateDomainDescription(tables: TableSchema[], relationships: TableRelationship[]): string {
    return `包含${tables.length}个数据表的业务领域，主要处理${tables.map(t => t.name).join('、')}相关的业务逻辑`
  }

  private suggestModules(tables: TableSchema[]): string[] {
    const modules: string[] = []
    
    tables.forEach(table => {
      const moduleName = this.toCamelCase(table.name) + 'Module'
      modules.push(moduleName)
    })
    
    return modules
  }

  private toCamelCase(str: string): string {
    return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())
      .replace(/^[a-z]/, letter => letter.toUpperCase())
  }

  private async callAIService(prompt: string): Promise<string> {
    // 这里实现具体的AI服务调用
    // 可以集成OpenAI、Claude、或本地模型
    
    // 模拟响应
    return `
// 生成的代码示例
@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(nullable = false)
    private String username;
    
    // ... 其他字段和方法
}
    `
  }

  private parseAIResponse(response: string): GeneratedCode[] {
    // 解析AI返回的代码，分类整理
    return [
      {
        type: 'model',
        filename: 'User.java',
        content: response,
        description: '用户实体类',
        dependencies: ['javax.persistence.*']
      }
    ]
  }
}

export const aiCodeGeneratorService = new AICodeGeneratorService()



